package ucl.cs.stockBroker.server;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import ucl.cs.stockBroker.common.Account;

public class ServerWriter implements Runnable {
	private Account account;
	private Map<Integer, Account> accounts;
	private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
	private final Lock w = rwl.writeLock();

	public ServerWriter(Map<Integer, Account> accounts) {
		this.accounts = accounts;
	}

	public void run() {
		w.lock();
		writeAccounts();
		w.unlock();
	}

	private void writeAccounts() {
		try {

			OutputStream fout = new FileOutputStream("data/info.xml");
			OutputStream bout = new BufferedOutputStream(fout);
			OutputStreamWriter out = new OutputStreamWriter(bout, "8859_1");

			out.write("<accounts\r\n>");

			for (int i = 0; i < accounts.size(); i++) {
				account = accounts.get(i);
				out.write("<account>\r\n");

				out.write("<name>" + account.getName() + "</name>\r\n");
				out.write("<pin>" + PINCipher.encryptPin(account.getPin())
						+ "</pin>\r\n");
				out
						.write("<balance>" + account.getBalance()
								+ "</balance>\r\n");

				for (Map.Entry<String, Integer> share : account.getShares()
						.entrySet()) {
					out.write("<share>\r\n");
					out.write("<symbol>" + share.getKey() + "</symbol>\r\n");
					out.write("<quantity>" + share.getValue()
							+ "</quantity>\r\n");
					out.write("</share>\r\n");
				}

				out.write("</account>\r\n");
			}
			out.write("</accounts>");

			out.flush();
			out.close();

		} catch (IOException e) {
			System.out.println(e.getMessage());
		}

	}

}
